package base.Chapter00_Structures.C05_Queue;

/**
 * 顺序队列-数组实现
 * <p>
 * 属性列表
 * 1，capacity = 10
 * 2，head = 0
 * 3，tail = 0
 * 4, container[]
 * <p>
 * <p>
 * 功能列表
 * 1，入队
 * 判断是否已满
 * tail++
 * tail到达队列边界到时候，触发移动
 * <p>
 * 2，出队
 * 判断是否为空
 * head++
 */
public class ArrayQueue {
    private final int capacity;
    private int head;
    private int tail;
    private final String[] container;

    public ArrayQueue(int capacity) {
        this.capacity = capacity;
        container = new String[capacity];
        head = 0;
        tail = 0;
    }

    public boolean enqueue(String e) {
        //Check: isFull
        if (tail == capacity && head == 0) {
            return false;
        }
        //Check: 是否需要移动数据
        if (head > 0) {
            //移动
            int length = tail - head;
            System.arraycopy(container, head, container, 0, length);
            tail -= head;
            head = 0;
        }
        // 有空间， 插入到尾部
        container[tail++] = e;
        return true;
    }

    public String dequeue() {
        // Check: isEmpty
        if (tail == head) {
            return null;
        }
        return container[head++];
    }
}
